<template>
  <div id="PictureManagePage">
    <a-flex justify="space-between">
      <h2>图片管理</h2>
      <div class="createBtn">
        <a-button type="primary" href="/add_picture" target="_blank">+ 创建图片</a-button>
        <a-button type="primary" href="/add_picture/batch" target="_blank" ghost style="margin-left: 5px">+ 批量上传图片</a-button>
      </div>
    </a-flex>
    <!--    搜索功能-->
    <div class="searchModel">
      <a-form layout="inline" :model="searchParams" @finish="doSearch">
        <a-form-item label="关键词" name="searchText">
          <a-input
            v-model:value="searchParams.searchText"
            placeholder="从名称和简介搜索"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="类型" name="category">
          <a-input v-model:value="searchParams.category" placeholder="请输入类型" allow-clear />
        </a-form-item>
        <a-form-item label="标签" name="tags">
          <a-select
            v-model:value="searchParams.tags"
            mode="tags"
            placeholder="请输入标签"
            style="min-width: 180px"
            allowClear
          />
        </a-form-item>
        <a-form-item label="审核状态" name="reviewStatus">
          <a-select v-model:value="searchParams.reviewStatus" :options="PIC_REVIEW_STATUS_OPTIONS" placeholder="请选择审核状态" style="min-width: 180px" allow-clear/>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-form-item>
      </a-form>
    </div>
    <!--    图片管理模块-->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 1500 }"
    >
      <template #headerCell="{ column }"></template>

      <template #bodyCell="{ column, record }">
        <!--        设置图片url展示-->
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="100" />
        </template>
        <!--        设置标签格式化展示-->
        <template v-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!--        设置图片信息-->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>比例：{{ record.picScale }}</div>
          <div>大小：{{ formatSize(record.picSize) }}</div>
        </template>
        <!--        设置审核信息展示方式-->
        <template v-if="column.dataIndex === 'reviewMessage'">
          <div class="reviewTag">
            <a-tag :color="record.reviewStatus === 0 ? 'processing' : record.reviewStatus === 1 ? 'success' : 'error'">
              <template #icon>
                <sync-outlined v-if="record.reviewStatus === 0"/>
                <check-circle-outlined v-if="record.reviewStatus === 1"/>
                <close-circle-outlined v-if="record.reviewStatus === 2"/>
              </template>
              {{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}
            </a-tag>
          </div>
          <div>{{ record.reviewMessage }}</div>
          <div v-if="record.reviewerId">审核人：{{ record.reviewerId }}</div>
          <div v-if="record.reviewTime">
            审核时间：
            {{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm:ss') }}
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!--  按钮操作区  -->
        <template v-else-if="column.key === 'action'">
          <a-button
            v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
            type="link"
            @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
            >通过
          </a-button>
          <a-button
            v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
            type="link"
            @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
            >拒绝
          </a-button>
          <a-button type="link" :href="`/add_picture?id=${record.id}`" target="_blank"
            >编辑</a-button
          >
          <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  listPictureByPageUsingPost,
} from '@/api/PictureController'
import { message } from 'ant-design-vue'
import {PIC_REVIEW_STATUS_ENUM, PIC_REVIEW_STATUS_MAP, PIC_REVIEW_STATUS_OPTIONS} from '@/constants/picture'
import {
  CheckCircleOutlined,
  SyncOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons-vue';
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import {formatSize} from "../../utils";

dayjs.locale('zh-cn')

// 搜索图片数据
const doSearch = () => {
  // 每次搜索从第一页开始搜，否则可能搜不到
  searchParams.current = 1
  fetchData()
}

//点击删除按钮删除记录操作
const doDelete = async (id: string) => {
  if (!id) return
  // 调用后端方法，根据id删除记录
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 再次获取数据刷新
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}

// 表格列标题定义
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '图片',
    dataIndex: 'url',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
  },
  {
    title: '审核状态',
    dataIndex: 'reviewMessage',
  },
  {
    title: '上传用户',
    dataIndex: 'userId',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

//获取图片数据接收
const dataList = ref<API.PictureVO>([]) //记录图片数组
const total = ref(0) // 总图片条数
// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 获取后端图片数据
const fetchData = async () => {
  const res = await listPictureByPageUsingPost({
    ...searchParams,
    nullSpaceId: true,
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取后端图片数据失败，' + res.data.message)
  }
}

// 让页面第一次刷新时获取一次，之后不必重复获取
onMounted(() => {
  fetchData()
})

//分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

/**
 * 修改审核状态
 * @param record
 * @param reviewStatus
 */
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员审核通过' : '管理员审核拒绝'
  // 给后端传入对应的参数
  const res = await doPictureReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  })
  if (res.data.code === 0) {
    message.success('审核成功')
    //刷新获取最新列表
    fetchData()
  } else {
    message.error('审核失败，' + res.data.message)
  }
}
</script>
<style scoped>
#PictureManagePage {
}

.searchModel {
  padding-bottom: 5px;
}
.reviewTag {
  text-align: center;
}

</style>
